package com.lk2.core.remoting
{
	import com.lk2.core.config.AbsConfigObj;
	import com.lk2.core.config.IConfig;
	import com.lk2.core.remoting.remotingAdapters.ColdFusionAdapter;
	import com.lk2.core.remoting.remotingAdapters.IRemoteObjectAdapter;
	
	import flash.events.EventDispatcher;
	
	import mx.messaging.Channel;
	import mx.messaging.ChannelSet;
	import mx.messaging.channels.AMFChannel;
	import mx.rpc.remoting.RemoteObject;

	
	/**
	 * The RemoteObjectFactory is a static class implementing Factory pattern 
	 * for Remote Object generation.
	 * This class allows generation of a RemoteObject without any need for a 
	 * pre-specified endpoint in services-config.xml
	 * 
	 * @author Luca Bianchi
	 * 
	 */
	public class RemoteObjectFactory 
	{
		private static var eventDispatcher:EventDispatcher;

		private static var _configObj:IConfig;
		public static var CFC_CONNECTOR:String = 'cfc';
		
		
		/**
		 * This method sets up factory static class, by injecting a configurator object.
		 * it has to be called before any other call to this factory, otherwise an Error is thrown.
		 * 
		 * @param configObj is the AbsConfigObj provided to retrive configuration parameters for remoting
		 * 
		 */
		public static function initialize(configObj:AbsConfigObj):void{
			_configObj = configObj;	
		}
		

		/**
		 * Is the static function which builds the Remote Object 
		 * @param connector Connector type which has to me injected
		 * @param serverObject Optional. Remote Service source URL
		 * @param username Optional. Remote Service username
		 * @param password Optional. Remote Service password
		 * @return a @see RemoteObject object
		 * 
		 */
		public static function getRemoteObject(connector:String, configObj:IConfig = null, serverObject:String=null, username:String=null, password:String=null):RemoteObject
		{
			if(configObj != null) _configObj = configObj;
		    if(_configObj != null){
			    var adapter:IRemoteObjectAdapter;
		    
				switch(connector){
				
					case CFC_CONNECTOR:
						adapter = new ColdFusionAdapter(_configObj);
						var endPoint:String = adapter.AMFENDPOINT; //"http://localhost/flex2gateway/";
						var cfcChannel:Channel = new AMFChannel(adapter.CHANNELID,adapter.AMFENDPOINT);
						var amfChannelSet:ChannelSet = new ChannelSet();
						amfChannelSet.addChannel(cfcChannel);
						var service:RemoteObject = new RemoteObject(adapter.DESTINATION);
            			service.channelSet = amfChannelSet;
            			service.source = serverObject; // If you are using ColdFusion
            			if((username != null)&&(password!=null))            
	            			service.setCredentials(username, password); // if you need it				
    	        	break;
				}
				return service;
			}else{
				throw new Error("This Factory has to be initialized before using. Please run RemoteObjectFactory.initialize() first");	
			}
		}
		

	}
}